import { useState } from 'react';
import { request } from '@/request';
import { ShareIcon, CopyIcon, InviteIcon } from '@/components/icons';
import { Modal } from '@/components';
import { useModal } from '@/hooks';
import { toast } from 'react-hot-toast';

const GroupShare = ({ groupId, groupName }) => {
   const [code, setCode] = useState('');
   const { isOpen, openModal, closeModal } = useModal();
   const handleGenCode = () => {
      request('/groups/genCode', {
         method: 'POST',
         data: {
            groupId,
         },
         success: (data) => {
            setCode(data.code);
            openModal();
         },
      });
   };

   const handleCopy = async () => {
      await navigator.clipboard.writeText(code);
      toast.success(`复制成功`);
   };

   return (
      <div>
         <ShareIcon type="primary" size={20} onClick={handleGenCode} />
         <Modal
            isOpen={isOpen}
            onClose={closeModal}
            showClose
            header={
               <div className="flex items-center justify-center">
                  <InviteIcon type="primary" size={20} className="mr-1" />
                  <span>邀请码{` -> `}</span>
                  <span className="ml-2">{groupName}</span>
               </div>
            }
         >
            <div
               className="text-xl space-x-2 flex items-end justify-center"
               onClick={handleCopy}
            >
               <span className="color-light tracking-widest">{code}</span>
               <CopyIcon type="light" />
            </div>
         </Modal>
      </div>
   );
};
export default GroupShare;
